package com.tensquare.user.controller;


import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import java.util.HashMap;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    //1.发送短信验证码
    @PostMapping("sendsms/{mobile}")
    public Result sendSms(@PathVariable String mobile){
        //1.1.调用服务执行发送验证码操作
        userService.sendSms(mobile);
        //1.2返回结果
        return new Result(true,StatusCode.OK,"验证码发送成功！");
    }

    //2.注册用户
    @PostMapping("register/{code}")
    public Result register(@PathVariable String code, @RequestBody User user){
        //2.1判断验证码是否正确
        boolean b =userService.isExistsCode(code,user.getMobile());
        //2.2验证码错误的情况
        if(!b){
            return new Result(false,StatusCode.ERROR,"输入验证码错误！");
        }
        //2.3验证码正确的情况，将用户添加到数据库
        userService.add(user);
        //2.4返回结果
        return new Result(true,StatusCode.OK,"注册成功！");
    }

    //3.用户登录
    @PostMapping("login")
    public Result login(@RequestBody User user){
        //3.1判断用户是否登录
        User loginUser=userService.login(user);
        //3.2判断是否为空，不为空说明成功登录
        if(loginUser!=null){
            //3.2.1调用工具类获取token字符串
            String token = jwtUtil.getToken(loginUser.getId(), loginUser.getNickname(), "user");
            //3.2.2定义封装数据的map对象
            HashMap hashMap = new HashMap();
            hashMap.put("token",token);
            hashMap.put("name",loginUser.getNickname());
            return new Result(true,StatusCode.OK,"登录成功！",hashMap);
        }
        //3.3为空则登录失败
        return new Result(true,StatusCode.OK,"登录失败！");
    }

    //4.更新粉丝数
    @PostMapping("incfans/{userId}/{num}")
    public Result incfans(@PathVariable String userId,@PathVariable int num){
        //1.调用服务更新粉丝数
        userService.incfans(userId,num);
        //2.返回结果
        return new Result(true,StatusCode.OK,"更新粉丝数成功!");
    }

    //5.更新关注数
    @PostMapping("incfollow/{userId}/{num}")
    public Result incfollow(@PathVariable String userId,@PathVariable int num){
        //1.调用服务更新关注数
        userService.incfollow(userId,num);
        //2.返回结果
        return new Result(true,StatusCode.OK,"更新关注数成功！");
    }

}
